package com.springboot.study.config;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableRabbit
public class RabbitConfig {
    /**
     * 创建 RabbitTemplate，用于发送消息
     */
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        // 注意：这里使用的是 Spring 的 ConnectionFactory，不是 com.rabbitmq.client.ConnectionFactory
        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        // 设置消息转换器（将对象自动转换成 JSON）
        template.setMessageConverter(new Jackson2JsonMessageConverter());
        // 设置发送确认回调
        template.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                System.out.println("消息发送成功");
            } else {
                System.out.println("消息发送失败：" + cause);
            }
        });
        // 可选：设置消息无法路由到队列时的回调
        template.setReturnsCallback(returned -> {
            System.out.println("消息路由失败: " + returned.getMessage());
        });
        return template;
    }
}
